using System.Collections.Generic;
using JigLibX.Physics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace SolarWinds.Renderers
{
    public class PhysicsDebugRenderer : DrawableGameComponent
    {
        BasicEffect mBasicEffect;
        readonly List<VertexPositionColor> mVertexData;
        private StateBlock mStateBlock;

        public PhysicsDebugRenderer(Game game)
            : base(game)
        {
            mVertexData = new List<VertexPositionColor>();
        }

        public override void Initialize()
        {
            base.Initialize();

            mBasicEffect = new BasicEffect(GraphicsDevice, null);
            GraphicsDevice.VertexDeclaration = new VertexDeclaration(GraphicsDevice, VertexPositionColor.VertexElements);

            mStateBlock = new StateBlock(GraphicsDevice);
        }

        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);

            mVertexData.Clear();

            foreach (Body body in PhysicsSystem.CurrentPhysicsSystem.Bodies)
            {
                Vector3 pos = body.Position;  

                mVertexData.Add(new VertexPositionColor(pos, Color.CornflowerBlue));
            } 
        }

        public override void Draw(GameTime gameTime)
        {
            base.Draw(gameTime);

            if (mVertexData.Count == 0 || !Enabled) return;

            mStateBlock.Capture();

            mBasicEffect.AmbientLightColor = Vector3.One;
            mBasicEffect.View = SolarWindsGame.Camera.View;
            mBasicEffect.Projection = SolarWindsGame.Camera.Projection;
            mBasicEffect.VertexColorEnabled = true;

            GraphicsDevice.RenderState.PointSize = 10;
            GraphicsDevice.RenderState.DepthBufferWriteEnable = false;
            GraphicsDevice.RenderState.DepthBufferEnable = false;

            
            mBasicEffect.Begin();
            foreach (EffectPass pass in mBasicEffect.CurrentTechnique.Passes)
            {
                pass.Begin();

                GraphicsDevice.DrawUserPrimitives(PrimitiveType.PointList,
                                                  mVertexData.ToArray(), 0, mVertexData.Count - 1);

                pass.End();
            }
            mBasicEffect.End();

            mStateBlock.Apply();
            
            


        }
    }
}